package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.task.AmqpConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 设备数据上报Service业务层处理
 *
 * @author waker
 * @date 2025-09-18
 */
@Slf4j
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService, AmqpConsumer {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService iDeviceService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据上报
     *
     * @param id 设备数据上报主键
     * @return 设备数据上报
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备数据上报列表
     *
     * @param dto 设备数据上报
     * @return 设备数据上报
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto) {
        return lambdaQuery().like(StrUtil.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StrUtil.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(ObjectUtil.isNotEmpty(dto.getStartTime()) && ObjectUtil.isNotEmpty(dto.getEndTime()), DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .list();
    }

    /**
     * 新增设备数据上报
     *
     * @param deviceData 设备数据上报
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据上报
     *
     * @param deviceData 设备数据上报
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据上报
     *
     * @param ids 需要删除的设备数据上报主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据上报信息
     *
     * @param id 设备数据上报主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量插入设备上报数据
     *
     * @param notifyData
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData notifyData) {
        // 1. 根据设备id查询设备信息
        String deviceId = notifyData.getHeader().getDeviceId();
        Device device = iDeviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        // 2. 判断设备是否存在
        if (ObjectUtil.isEmpty(device)) {
            log.error("设备不存在,设备id: {}", deviceId);
            return;
        }
        // 3. 批量插入设备上报数据 （一个设备可以有多个上报数据）
        List<IotMsgService> services = notifyData.getBody().getServices();
        try {
            for (IotMsgService service : services) {
                Map<String, Object> properties = service.getProperties();
                if (ObjectUtil.isEmpty(properties)) {
                    continue;
                }
                // 3.1 处理上报时间
                LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
                LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                // 3.2 处理上报属性数据
                List<DeviceData> deviceDataList = new ArrayList<>(properties.size());
                properties.forEach((k, v) -> {
                    if (k.contains("Time")) {
                        v = LocalDateTimeUtil.format(LocalDateTime.parse(v.toString(), DateTimeFormatter.ISO_DATE_TIME), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    }
                    DeviceData deviceData = DeviceData.builder()
                            .iotId(deviceId)
                            .functionId(k)
                            .dataValue(v.toString())
                            .alarmTime(alarmTime)
                            .accessLocation(device.getRemark())
                            .build();
                    BeanUtil.copyProperties(device, deviceData, "id", "createBy", "updateBy", "createTime", "updateTime");
                    deviceDataList.add(deviceData);
                });
                saveBatch(deviceDataList);
                //存储到redis中deviceDataList
                //hash 结构来进行存储  大key  小key  value
                redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, deviceDataList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 消费者 用于多消费者监听同一个队列的消息（实现同一个接口）
     *
     * @param notifyData
     */
    @Override
    public void consumer(IotMsgNotifyData notifyData) {
        batchInsertDeviceData(notifyData);
    }
}
